<?php
namespace control;
/*
*成本分摊单类
*/

class costAllocationClass extends adIndexClass
{
    private const page = 'costAllocation';
    private const table = 'cost_allocation';//成本分摊主表
    private const table_price = 'cost_allocation_price';//单价表
    private const table_source = 'cost_allocation_source';//源单表
    private const table_item = 'cost_allocation_item';//费用项目表
    private const title = '成本分摊单';
    private array $typeOption = ['按数量', '按销售总价'];//分摊方式

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 350,
                        'sort' => 1,
                    ],
                    'recordDate'  => [
                        'name'  => '单据日期',
                        'width' => 350,
                        'sort' => 1,
                    ],
                    'money'         => [
                        'name'  => "分摊费用合计(". static::$unit . ")",
                        'width' => 350,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 350,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            'coid' => self::$coid,
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'money':
                        $money = find(array('table' => self::table_item, 'where' => "orderId = '$array[id]'", 'sum' => "money"));
                        $row[] = self::lostZero($money);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table_item,
            'single' => " orderId in (select id from ".self::table." where 1=1 {$where}) ",
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'        => self::formattingFigure($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $tr[] = ['', '费用项目', '费用总额(' . static::$unit . ')', '备注'];
        $result = find(array(
            'field' => "id as mxId,item,money,text as mxText",
            'table' => self::table_item." where orderId = '$info[id]' order by list"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['money'] = self::lostZero($array['money']);
                $array['list'] = $k+1;
                $tr[] = $this->listRow($array);
            }
        }else{
            $tr[] = $this->listRow(['mxId'=>self::getId(), 'list'=>1]);
        }


        $sourceTr[] = ['', '单据日期', '单据编号', '加工类型', '生产线', '存货类别', '物料编码', '物料名称', '规格型号', '单位', '计划数量', '合格数量', '报废数量', 'BOM版本'];
        $result = find(array('table' => self::table_source, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $k=>$array) {
            $mx = query('machining_order', "id = '$array[sourceId]'");
            $machining_mx = query('machining_order_mx', "id = '$array[sourceMxId]'");
            $line = query('product_line', "id = '$mx[lineId]'");
            $material = query('material', "id = '$machining_mx[materialId]'");
            $bom = query('bom', "id = '$machining_mx[bomId]'");
            $passNum = $this->getMaterialNum($machining_mx['id'], $machining_mx['unit']);
            $scrapNum = $this->getMaterialNum($machining_mx['id'], $machining_mx['unit'], '报废');
            $sourceTr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this)").
                hidden(array('name' => 'detailId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'sourceId[]', 'value' => $array['sourceMxId'])),
                $mx['recordDate'],
                $mx['orderNo'],
                $mx['type'],
                $line['workshop'] . '-' . $line['name'],
                $material['subject'],
                $material['code'],
                $material['name'],
                $material['model'],
                $machining_mx['unit'],
                self::lostZero($machining_mx['num'],'numPrecision'),
                $passNum,
                $scrapNum,
                $bom['bomVersion']
            ];
        }
        $list = $this->listTable(array('tr' => $sourceTr, 'end' => true));
        $but = <<<efo
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addOrder',$('form[name=costAllocationEditForm]').serialize())">关联源单</span>
efo;

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "分摊方式：" => radio(array('name' => 'type', 'value' => $this->typeOption, 'checked' => $info['type'] ?: $this->typeOption[0])),
                    must . "单据日期：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '源单据',
            'button' => $but,
            'html' => $list,
        ]);
        $body .= $this->editList([
            'title' => '待摊费用',
            'html' => $this->listTable(array('tr' => $tr, 'end' => true)),
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= <<<efo
<script>
function addRow(e){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{},function (res){
            $(e).closest('tr').after(res.data);
            resetNumber($(e).closest('tbody'))
         },'json');
}
function addOrder(){
     $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addOrderEdit',$("form[name='orderForm']").serialize(),function (res){
           $('#costAllocationAddOrder').hide()
           $("#materialTable tbody").append(res.html);
         },'json');
}
</script>

efo;
        //返回
        return $this->tab($data);
    }

    /**
     * 获取合格/报废数量
     * @param $machiningOrderMxId
     * @param $unit
     * @param string $type
     * @return float|int
     */
    public function getMaterialNum($machiningOrderMxId, $unit, $type = '合格'): float|int
    {
        $num = 0;
        $all = find(array('table' => "machining_in_order_detail as a join machining_in_order as b on a.orderId = b.id", 'field' => "a.*", 'where' => "a.coid = '" . self::$coid . "' and sourceId = '$machiningOrderMxId'"));
        foreach ($all['array'] as $array) {
            if ($type == '合格') {
                $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$array[id]' and coid = '" . self::$coid . "'"));
                foreach ($inventoryAll['array'] as $item) {
                    $num += machiningOrderClass::material_num_change($item['materialId'], $item['unit'], $unit, $item['num']);
                }
            } elseif ($type == '报废') {
                $quality_orderAll = find(array('table' => 'quality_order', 'where' => "sourceMxId = '$array[id]' and type = 2 and coid = '" . self::$coid . "' and state = '已质检'"));
                foreach ($quality_orderAll['array'] as $item) {
                    $tempNum = ($item['num'] - $item['passNum']);
                    $num += machiningOrderClass::material_num_change($item['materialId'], $item['unit'], $unit, $tempNum);
                }
            }

        }
        return $num;
    }

    /**
     * Desc : 待摊费用
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function listRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['mxId'])&&$data['mxId']?$data['mxId']:self::getId();
        $field = ['item', 'money', 'mxText'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'listRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this)"),
            hidden(array('name' => 'mxId[]', 'value' => $mxId)) .
            select(array('name' => 'item[]', 'title' => '请选择', 'option' => explode('，', para('feeItemOption')), 'value' => $array['item'])),
            text(array('name' => 'money[]', 'type' => 'number', 'value' => $array['money'])),
            text(array('name' => 'mxText[]', 'value' => $array['mxText']))
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $res = json_decode($this->listRow(),true);
        $html = $res['html'];
        $json['data'] = $html;
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $itemArr = $this->post('item');
        $moneyArr = $this->post('money') ?: [];
        $mxTextArr = $this->post('mxText');
        //源单
        $detailIdIdArr = $this->post('detailId') ?: [];
        $sourceIdArr = $this->post('sourceId');

        $field = [
            'type' => $this->post('type'),
            'recordDate' => $this->post('recordDate'),
        ];
        $annotation = [
            'type' => '分摊方式',
            'recordDate' => '单据日期',
        ];
        $rules = [
            'type' => 'required',
            'recordDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请填写分摊信息';
        } elseif (static::is_null_array($itemArr)) {
            $json['warn'] = '请选择费用项目';
        } elseif (static::is_null_array($moneyArr)) {
            $json['warn'] = '请填写费用总额';
        } elseif (static::is_null_array($detailIdIdArr)) {
            $json['warn'] = '请选择源单';
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = '此成本分摊单已确认，不能修改';
        } else {
            $this->startTrans();
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'CBFT' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '".self::$coid."'",
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'state' => '草稿',
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }

            //费用项
            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::table_item, "id = '$nid'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::table_item,
                        "field" => [
                            'item' => $itemArr[$k],
                            'money' => $moneyArr[$k],
                            'text' => $mxTextArr[$k],
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::table_item,
                        "field" => [
                            'id' => $nid,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'item' => $itemArr[$k],
                            'money' => $moneyArr[$k],
                            'text' => $mxTextArr[$k],
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }
            //源单
            foreach ($detailIdIdArr as $k => $mxId) {
                $mx = query(self::table_source, "id = '$mxId'");
                $machiningMx = query('machining_order_mx',"id = '$sourceIdArr[$k]'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::table_source,
                        "field" => [
                            'sourceId' => $machiningMx['orderId'],
                            'sourceMxId'=>$sourceIdArr[$k]
                        ],
                        "where" => " id = '$mxId'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::table_source,
                        "field" => [
                            'id' => $mxId,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'sourceId' => $machiningMx['orderId'],
                            'sourceMxId'=>$sourceIdArr[$k]
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::table_item, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                delete(array('table' => self::table_source, 'where' => " id not in ('" . implode("','", $detailIdIdArr) . "') and orderId = '$id'"));
                delete(array('table'=>self::table_price,'where'=>"orderId = '$id'"));
                //计算分摊单价
                match ($field['type']){
                    '按数量'=>$this->numType($id),
                    '按销售总价'=>$this->saleType($id),
                    default=>'未找到类型',
                };

                if ($json['warn'] =='新增成功'){
                    auditClass::operateRecord($id,"成本分摊单",'新建');
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 关联源单
     * @return bool|string
     */
    public function addOrder(): bool|string
    {
        $html =
            select(array("name" => "orderType", "title" => "源单类型", 'option' => ['生产计划' => '生产计划单', '半成品' => '半成品加工单'])) .
            text(array("name" => "orderNo", "title" => "源单编号")) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "单据日期-单据日期")) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addOrder()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button));
    }

    /**
     * 关联源单
     * @return bool|string
     */
    public function addOrderSearch(): bool|string
    {
        $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        $where = "a.id not in ('" . implode("','", $sourceId) . "')";
        $and = '';
        $like = [
            'b.orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'b.state' => '已确认',
            'b.orderType' => $this->post('orderType'),
            'a.coid' => self::$coid,
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;

        $page = $this->page([
            "table" => "machining_order_mx as a join machining_order as b on a.orderId = b.id",
            'field' => 'a.*,b.orderType,b.orderNo,b.recordDate,b.lineId',
            "where" => $where,
            'pageNum' => 50,
            "order" => "b.recordDate desc,b.orderNo desc,a.list asc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("orderForm", "orderId");
        $tr[] = [$checkAll, '源单类型', '源单编号', '单据日期', '生产线', '存货类别', '物料编码', '物料名称', '规格型号', '单位'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "orderId", "value" => $array['id']),
            );
            $material = query('material', "id = '$array[materialId]'");
            $line = query('product_line', "id = '$array[lineId]'");
            $tr[] = array(
                $this->dominate($dominate),
                $array['orderType'] == '生产计划' ? '生产计划单' : '半成品加工单',
                $array['orderNo'],
                $array['recordDate'],
                $line['workshop'] . '-' . $line['name'],
                $material['subject'],
                $material['code'],
                $material['name'],
                $material['model'],
                $array['unit']
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='orderForm'>" .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 关联源单
     */
    public function addOrderEdit(): bool|string
    {
        $mxIdArr = $this->post('orderId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择源单';
        } else {
            $tr = [];
            foreach ($mxIdArr as $id) {
                $machining_order_mx = query('machining_order_mx', "id = '$id'");
                $machining_order = query('machining_order', "id = '$machining_order_mx[orderId]'");
                $type = $machining_order['orderType'] == '生产计划' ? '生产计划单' : '半成品加工单';
                $line = query('product_line', "id = '$machining_order[lineId]'");
                $material = query('material', "id = '$machining_order_mx[materialId]'");
                $bom = query('bom', "id = '$machining_order_mx[bomId]'");
                $uid = self::getId();
                $passNum = $this->getMaterialNum($machining_order_mx['id'], $machining_order_mx['unit']);
                $scrapNum = $this->getMaterialNum($machining_order_mx['id'], $machining_order_mx['unit'], '报废');
                $machining_order_mx['num'] = self::lostZero($machining_order_mx['num'],'numPrecision');
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this)").
                    hidden(array('name' => 'detailId[]', 'value' => $uid)) .
                    hidden(array('name' => 'sourceId[]', 'value' => $id)),
                    $machining_order['recordDate'],
                    $machining_order['orderNo'],
                    $type,
                    $line['workshop'].'-'.$line['name'],
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $machining_order_mx['unit'],
                    self::lostZero($machining_order_mx['num'],'numPrecision'),
                    $passNum,
                    $scrapNum,
                    $bom['bomVersion']?:'-',
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] != '已确认') {
                if ($this->power(self::page, "edit")) {
                    if ($info['state'] == '草稿') {
                        //按钮
                        $button[] = [
                            "name" => "提交",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "operate",
                            "post" => ["act" => 'commit', "id" => $info['id']],
                            'style' => 'li-btn-blue-bg',
                        ];
                    }
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],

                    ];

                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }


            if ($this->power(self::page, "cancel") && $info['state'] == '已确认') {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $tr[] = ['费用项目', '费用总额(' . static::$unit . ')', '备注'];
            $result = find(array('table' => self::table_item, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $tr[] = [
                    $array['item'],
                    $array['money'],
                    $array['text'],
                ];
            }
            $income = find(array('table' => self::table_item, 'sum' => "money", 'where' => "orderId = '$info[id]'"));
            $total_tr = [
                    1=>self::lostZero($income),
                ];
            $sourceTr[] = ['单据日期', '单据编号', '加工类型', '生产线', '存货类别', '物料编码', '物料名称', '规格型号', '单位', '计划数量', '合格数量', '报废数量', '分摊金额','BOM版本'];
            $result = find(array('table' => self::table_source, 'where' => "orderId = '$info[id]' order by list"));
            $totalArr = ['num'=>0,'passNum'=>0,'scrapNum'=>0];
            foreach ($result['array'] as $array) {
                $mx = query('machining_order', "id = '$array[sourceId]'");
                $machining_mx = query('machining_order_mx', "id = '$array[sourceMxId]'");
                $line = query('product_line', "id = '$mx[lineId]'");
                $material = query('material', "id = '$machining_mx[materialId]'");
                $bom = query('bom', "id = '$machining_mx[bomId]'");
                $passNum = $this->getMaterialNum($machining_mx['id'], $machining_mx['unit']);
                $scrapNum = $this->getMaterialNum($machining_mx['id'], $machining_mx['unit'], '报废');
                $money = find(array('table'=>self::table_price,'where'=>"orderId = '$info[id]' and machiningOrderMxId='$array[sourceMxId]'",'sum'=>"money"));
                $sourceTr[] = [
                    $mx['recordDate'],
                    $mx['orderNo'],
                    $mx['type'],
                    $line['workshop'] . '-' . $line['name'],
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $machining_mx['unit'],
                    self::lostZero($machining_mx['num'],'numPrecision'),
                    $passNum,
                    $scrapNum,
                    $money,
                    $bom['bomVersion']
                ];
                $totalArr['num'] += $machining_mx['num'];
                $totalArr['passNum'] += $passNum;
                $totalArr['scrapNum'] += $scrapNum;
            }
            $disMoney = find(array('table'=>self::table_price,'where'=>"orderId = '$info[id]'",'sum'=>"money"));
            $total_source_tr = [
                    9=>self::lostZero($totalArr['num'],'num'),
                    10=>self::lostZero($totalArr['passNum'],'num'),
                    11=>self::lostZero($totalArr['scrapNum'],'num'),
                    12=>self::lostZero($disMoney),
                ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "分摊方式" => $info['type'],
                        "单据日期" => $info['recordDate'],
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state']
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '源单据',
                'html' => $this->listTable(array('tr' => $sourceTr, 'showEmpty' => true, 'total' => $total_source_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '分摊费用',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /**
     * 确认
     */
    public function confirmEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此成本分摊单';
        }  elseif ($info['state'] != '待确认') {
            $json['warn'] = '此成本分摊单不是待确认状态，不能确认';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
//            //计算分摊单价
//            $bool = match ($info['type']){
//                '按数量'=>$this->numType($info['id']),
//                '按销售总价'=>$this->saleType($info['id']),
//                default=>'未找到类型',
//            };
//            if ($bool !==true){
//                $json['warn'] = $bool;
//            }
            if (in_array($json['warn'], ["更新成功"])) {
                $this->commitTrans();
                auditingFollow(array(
                    "type" => "成本分摊单",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】确认",
                    'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                    'staffName' => $this->control['name'],
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] ='确认成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 按销售总价
     * @param $id
     * @return bool|string
     */
    private function saleType($id): bool|string
    {
        $all = find(array('table'=>self::table_source,'where'=>"orderId = '$id'"));
        $totalMoney = 0;
        $totalNum = 0;
        $temp = [];
        $moneyTemp = [];
        foreach ($all['array'] as $array){
            $machiningOrderMx = query('machining_order_mx',"id = '$array[sourceMxId]'");
            $temp[$array['sourceMxId']] = 0;
            $moneyTemp[$array['sourceMxId']] = 0;
            $machiningInAll = find(array(
                'table'=>'machining_in_order as a join machining_in_order_detail as b on a.id = b.orderId',
                'field'=>"b.*",
                'where'=>" a.coid = '".self::$coid."' and a.state = '已确认' and b.sourceId = '$array[sourceMxId]'"
            ));
            foreach ($machiningInAll['array'] as $item){
                $inventoryAll = find(array('table'=>'inventory_detail','where'=>"sourceId = '$item[id]' and coid = '".self::$coid."'"));
                foreach ($inventoryAll['array'] as $val){
                    $material = query('material',"id = '$val[materialId]'");
                    $num=machiningOrderClass::material_num_change($val['materialId'],$material['unit'],$machiningOrderMx['unit'],$val['num']);
                    $totalNum+=$num;
                    $totalMoney +=$num*$material['salePrice'];
                    $temp[$array['sourceMxId']] += $num;
                    $moneyTemp[$array['sourceMxId']] += $num*$material['salePrice'];
                }
            }
        }
        if ($totalNum==0){
            return '未找到入库数量';
        }
        $all = find(array('table'=>self::table_item,'where'=>"orderId = '$id'"));
        foreach ($all['array'] as $array){
            foreach ($moneyTemp as $machiningMxId => $mxMoney){
                $source = query(self::table_source,"orderId = '$id' and sourceMxId = '$machiningMxId'");
                $machiningMx = query('machining_order_mx',"id = '$source[sourceMxId]'");
                $price =$temp[$machiningMxId]>0&&$totalMoney>0?round($mxMoney/$totalMoney*$array['money']/$temp[$machiningMxId],2):0;
                $warn = static::insert(array(
                    'table'=>self::table_price,
                    'field'=>[
                        'id'=>suiji(),
                        'coid'=>self::$coid,
                        'orderId'=>$id,
                        'machiningOrderId'=>$source['sourceId'],
                        'machiningOrderMxId'=>$source['sourceMxId'],
                        'materialId'=>$machiningMx['materialId'],
                        'price'=>$price,
                        'itemId'=>$array['id'],
                        'unit'=>$machiningMx['unit'],
                    ]
                ));
                if ($warn !='新增成功'){
                    return '成本分摊失败';
                }
//                $warn = update(array('table'=>'inventory_detail','field'=>['price'=>$price],'where'=>"sourceId in (select id from machining_in_order_detail where sourceId = '$machiningMxId')'"));
//                if ($warn !='更新成功'){
//                    return '修改入库单价失败';
//                }
            }
        }

        return true;
    }

    /**
     * 按数量
     */
    private function numType($id): bool|string
    {
        $all = find(array('table'=>self::table_source,'where'=>"orderId = '$id'"));
        $num = 0;
        $temp = [];
        foreach ($all['array'] as $array){
            $temp[$array['sourceMxId']] = 0;
            $machiningMx = query('machining_order_mx',"id = '$array[sourceMxId]'");
            $machiningInAll = find(array('table'=>'machining_in_order as a join machining_in_order_detail as b on a.id = b.orderId','field'=>"b.*",'where'=>" a.coid = '".self::$coid."' and a.state = '已确认' and b.sourceId = '$array[sourceMxId]'"));
            foreach ($machiningInAll['array'] as $item){
                $inventoryAll = find(array('table'=>'inventory_detail','where'=>"sourceId = '$item[id]' and coid = '".self::$coid."'"));
                foreach ($inventoryAll['array'] as $val){
                    $num+=machiningOrderClass::material_num_change($val['materialId'],$val['unit'],$machiningMx['unit'],$val['num']);
                    $temp[$array['sourceMxId']] += machiningOrderClass::material_num_change($val['materialId'],$val['unit'],$machiningMx['unit'],$val['num']);
                }
            }
        }
        if ($num==0){
            return '未找到入库数量';
        }
        $all = find(array('table'=>self::table_item,'where'=>"orderId = '$id'"));
        foreach ($all['array'] as $array){
            foreach ($temp as $machiningMxId => $n){
                $source = query(self::table_source,"orderId = '$id' and sourceMxId = '$machiningMxId'");
                $machiningMx = query('machining_order_mx',"id = '$source[sourceMxId]'");
                $money = round($n/$num*$array['money'],2);
                $price = $n>0?round($n/$num*$array['money']/$n,2):0;
                $warn = static::insert(array(
                    'table'=>self::table_price,
                    'field'=>[
                        'id'=>suiji(),
                        'coid'=>self::$coid,
                        'orderId'=>$id,
                        'machiningOrderId'=>$source['sourceId'],
                        'machiningOrderMxId'=>$source['sourceMxId'],
                        'materialId'=>$machiningMx['materialId'],
                        'price'=>$price,
                        'money'=>$money,
                        'num'=>$n,
                        'itemId'=>$array['id'],
                        'unit'=>$machiningMx['unit'],
                    ]
                ));
                if ($warn !='新增成功'){
                    return '成本分摊失败';
                }
//                $warn = update(array('table'=>'inventory_detail','field'=>['price'=>$price],'where'=>"sourceId in (select id from machining_in_order_detail where sourceId = '$machiningMxId')"));
//                if ($warn !='更新成功'){
//                    return '修改入库单价失败';
//                }
            }
        }

        return true;
    }
    /**
     * 提交
     */
    public function commitEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此成本分摊单';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此成本分摊单不是草稿状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "成本分摊单",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】提交",
                    'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                    'staffName' => $this->control['name'],
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '提交成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }
    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => ''
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此车间考勤';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此车间考勤不是已确认状态，无需撤回';
        }/* elseif (static::total(array('table' => 'inventory', "where" => "sourceId = '$info[id]' and coid = '" . self::$coid . "' and state in ('部分出库','已出库')")) > 0) {
            $json['warn'] = '此车间考勤已存在有出库的单据，不能撤回';
        } */ else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "车间考勤",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】撤回",
                    'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                    'staffName' => $this->control['name']
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '撤回成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此成本分摊单，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此成本分摊单？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::table_item, "where" => " orderId = '$id' "));
                    delete(array("table" => self::table_source, "where" => " orderId = '$id' "));
                    delete(array("table" => self::table_price, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}

